package com.heyqing.topic.GetIntersectionNode_0160;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * ClassName:GetIntersectionNode
 * Package:com.heyqing.topic.GetIntersectionNode_0160
 * Description:
 *
 * @Date:2024/9/17
 * @Author:Heyqing
 */
public class GetIntersectionNode {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        Set<Integer> set = new HashSet<>();
        while (Objects.nonNull(headA) || Objects.nonNull(headB)) {
            int preorder = set.size();
            if (Objects.nonNull(headA)) {
                set.add(headA.hashCode());
                if (set.size() == preorder) return headA;
            }
            preorder = set.size();
            if (Objects.nonNull(headB)) {
                set.add(headB.hashCode());
                if (set.size() == preorder) return headB;
            }

            if (Objects.nonNull(headA)) headA = headA.next;
            if (Objects.nonNull(headB)) headB = headB.next;
        }
        return null;
    }
}
